<?php
declare (strict_types=1);

namespace app\middleware;

use app\api\exception\HttpExceptionHandle;
use app\common\auth\JwtAuth;
use app\common\lib\HttpError;
use app\common\lib\ResponseJson;
use Closure;
use Redis;
use think\exception\ValidateException;
use think\facade\Cache;
use think\facade\Config;

/**
 * | Notes：Jwt中间件
 * +----------------------------------------------------------------------
 * | PHP Version 7.2+
 * +----------------------------------------------------------------------
 * | Copyright (c) 2011-2020 https://www.xxq.com.cn, All rights reserved.
 * +----------------------------------------------------------------------
 * | Author: 和好 <389123492@qq.com>
 * +----------------------------------------------------------------------
 * | Date: 2020/4/19 14:53
 * +----------------------------------------------------------------------
 */
class Jwt
{
    use ResponseJson;

    public function handle($request, Closure $next)
    {
        $token = trim((string)$request->header('token'));

        if ($token == 123456) return $next($request);

        if (empty($token)) throw new HttpExceptionHandle(HttpError::NO_TOKEN_ERR);

        //Token限流
        // 限制次数。
        $limit = 1000;
        // 限制时间
        $limit_time = 60;
        $key = 'ip_limit:' . $token;
        $redis = new Redis();
        $check = $redis->exists($key);
        if ($check) {
            $count = $redis->incr($key);
            if ($count > $limit) {
                throw new ValidateException('请求频繁，请稍后再试!');
            }
        } else {
            $redis->incr($key);
            $redis->expire($key, $limit_time);
        }
    }

}